source('/home/jc148322/scripts/libraries/cool_functions.r')
library(SDMTools)
wd='/home/jc148322/frog_declines/SDM2/';setwd(wd)
out.dir='/home/jc148322/frog_declines/SDM2/images_diff/'; dir.create(out.dir)

timeline=c('Pre_decline','Post_decline')

cols=c('grey80','firebrick','forestgreen','goldenrod1')

species=list.files(paste(wd,timeline[2],'/models/',sep=''))
base.asc=read.asc.gz('/home/jc148322/frog_declines/SDM/Pre_decline/bioclim_12_15/models/acuti/output/ascii/current.76to05.asc.gz')		

w=round((length(species)+0.1)/2) # get the width of the image... 4.5 rounds to 4, so add 0.1 so that it will round to 5
png(paste(out.dir,'diff.test.png',sep=''),width=dim(base.asc)[1]*w, height=dim(base.asc)[2]*2, units='px', pointsize=20, bg='white')
par(mfrow=c(2,w),mar=c(5,5,10,5))
	

for (spp in species) {cat(spp,'\n')
	
	occur=NULL
	dif=NULL
	for (tt in timeline) { cat(tt,'\n')
		var.dir=paste(wd, tt, '/models/',spp,'/bioclim.01.02.03.04.05.06.07.08.09.10.11.12.13.14.15.16.17.18.19/',sep='');setwd(var.dir)
		threshold=read.csv('output/maxentResults.csv',as.is=T)
		threshold=threshold$Balance.training.omission..predicted.area.and.threshold.value.logistic.threshold
		
		tasc=read.asc.gz(paste('output/ascii/current.76to05.asc.gz', sep=''))
		tasc[which(tasc<=threshold)]=0; tasc[which(tasc>0)]=1
		if (tt==timeline[1]) { tasc[which(tasc<=threshold)]=0; tasc[which(tasc>0)]=1; dif=tasc}
		if (tt==timeline[2]) { tasc[which(tasc<=threshold)]=0; tasc[which(tasc>0)]=2; dif=dif+tasc}

		toccur=read.csv('occur.csv',as.is=T)
		if (tt==timeline[1]) pre=toccur else post=toccur
	}
	
	image(dif,ann=F,axes=F,col=cols,zlim=c(0,3))
	points(pre$long,pre$lat,pch=16,cex=2,col='black')
	points(post$long,post$lat,pch=16,cex=2,col='white')
	mtext(spp,line=1, side=3, cex=2.5)
		
	
}

dev.off()
